﻿using AutoMapper;
using MediatR;
using Sale.Api.Application.Command.ClientPrice;
using Sale.Domain;
using Sale.ErrorCode;
using Sale.Infrastructure.Implement;
using System.Threading;

namespace Sale.Api.Application.Handler.ClientPrice
{
    public class UpdateClientPriceHandler : IRequestHandler<UpdateClientPriceCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly DatabaseContext db;
        private readonly ILogger<UpdateClientPriceHandler> logger;

        public UpdateClientPriceHandler(IMapper mapper,DatabaseContext db,ILogger<UpdateClientPriceHandler> logger)
        {
            this.mapper = mapper;
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(UpdateClientPriceCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            var clinentPrice=db.SqlSugar.Queryable<ClientPriceModel>().Where(x=>x.ClientPriceId==request.ClientPriceId).First();
            clinentPrice = mapper.Map(request, clinentPrice);

            int r = await db.SqlSugar.Updateable(clinentPrice).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "客户单价修改成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "客户单价修改失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
